<?php
/**
 * Created by PhpStorm.
 * User: sojo
 * Date: 2017/12/27
 * Time: 12:45
 */

namespace App\Http\Admin\Administration\Controllers;

use App\Api\OA\Personnel\Models\Personnel;
use App\Http\Admin\Administration\Models\Flow;
use App\Http\Admin\Administration\Models\FlowConfig;
use App\Http\Admin\Administration\Models\Workflow;
use App\Http\Admin\Administration\Models\WorkflowCopy;
use App\Http\Admin\Personnel\Models\AddressList;
use Framework\BaseClass\Http\Admin\Controller;
use Framework\Extend\Helpers\Upload;

class WorkflowController extends Controller
{
    /**
     * 首页
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return $this->view('index');
    }

    /**
     * 新建流程
     * @author sojo
     * @param $type
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function create($type)
    {
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法新建, 账户还未关联到通讯录');
        $userId = $contacts['id'];
        $flow = new Flow();
        if(is_numeric($type)) $type = Flow::getFlowAbbr($type);

        // 页面打开
        if (request()->method() == 'GET') {
            $data['serial_number'] = $flow->generateSerialNumber($type);
            $data['job_resume_id'] = request('job_resume_id', 0);
            $data['job_recruitment_id'] = request('job_recruitment_id', 0);
            // 获取模板数据
            $template = Flow::getTemplate($type);
            $data = array_merge($data, $template);
            if ($type == 'tp') {
                // 获取岗位回调数据
                $userInfo = (new Personnel())->getEmployeeInfo($userId);
                $data['flow_info'] = $userInfo->toArray();
            }
            return $this->view('create-' . $type, $data);
        }

        // ajax 提交处理
        $companyId = session('current_operation_company_id');
        switch ($type) {
            case 'doc':
                $data = $this->getRequestParameters([
                    'title', 'content', 'operator_id'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                break;
            case 'lv':
                $data = $this->getRequestParameters([
                    'type', 'start_time', 'end_time', 'reasons'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids', 'operator_id']);
                // 和App同步, 其实title用不到...
                $data['title'] = Flow::getLeaveTypeStr($data['type']);
                break;
            case 'su':
                $data = $this->getRequestParameters([
                    'department_id', 'operator', 'file_name', 'file_number',
                    'file_type', 'seal_type', 'note'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids', 'operator_id']);
                // findgrid获取contacts控件默认有个oa_department_id, 防止重复, 参数用department_id, 这里转换回来
                $data['oa_department_id'] = $data['department_id'];
                break;
            case 'cu':
                $data = $this->getRequestParameters([
                    'operator_id', 'department_id', 'start_place', 'return_place', 'start_time', 'return_time', 'type',
                    'number', 'request', 'reasons', 'note'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                // findgrid获取contacts控件默认有个oa_department_id, 防止重复, 参数用department_id, 这里转换回来
                $data['oa_department_id'] = $data['department_id'];
                $data['branch_data'][] = [
                    'type'    => $data['type'],
                    'number'  => $data['number'],
                    'request' => $data['request'],
                ];
                break;
            case 'tp':
                $data = $this->getRequestParameters([
                    'operator_id', 'new_department', 'new_position', 'reason', 'adjust_time',
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                break;
            case 'rb':
                $data = $this->getRequestParameters([
                    'operator_id', 'money', 'type', 'details'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                $data['branch_data'][] = [
                    'money'   => $data['money'],
                    'type'    => $data['type'],
                    'details' => $data['details'],
                ];
                break;
            case 'eg':
                $data = $this->getRequestParameters([
                    'operator_id', 'start_time', 'end_time', 'reasons',
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                break;
            case 'bt':
                $data = $this->getRequestParameters([
                    'operator_id', 'start_time', 'end_time', 'reasons', 'destination'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                $data['branch_data'][] = [
                    'start_time'  => $data['start_time'],
                    'end_time'    => $data['end_time'],
                    'reasons'     => $data['reasons'],
                    'destination' => $data['destination']
                ];
                break;
            case 'hs':
                $data = $this->getRequestParameters([
                    'operator_id', 'start_time', 'end_time', 'reasons'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                break;
            case 'ws':
                $data = $this->getRequestParameters([
                    'operator_id', 'time', 'reason'
                ], ['image_url', 'enclosure_url', 'serial_number', 'copy_ids']);
                break;
            case 'in':  // 面试流程
                $data = $this->getRequestParameters([
                    'operator_id', 'resume_id', 'recruitment_id'
                ], [
                    'note', 'image_url', 'enclosure_url', 'serial_number', 'copy_ids'
                ]);
                break;
            default:
                return $this->ajaxFail('不支持的流程类型');
        }

        // 后台文件统一用enclosure_url上传, 这里区分图片和文件
        if (is_array($data['enclosure_url'])) {
            $fileList = $data['enclosure_url'];
            $enclosureList = [];
            $imageList = [];
            $imageExt = ['jpg', 'png'];
            foreach ($fileList as $item) {
                $ext = explode('.', $item)[1];
                if (in_array($ext, $imageExt)) {
                    array_push($imageList, $item);
                } else {
                    array_push($enclosureList, $item);
                }
            }
            $data['image_url'] = implode(',', $imageList);
            $data['enclosure_url'] = implode(',', $enclosureList);
        }

        // 审批人检查
        if ($userId == $data['operator_id']) return $this->ajaxFail('提交失败, 无法使用自己作为审批人');

        // 创建流程
        $flow->newFlow($type, $data, $userId, $companyId);
        return $this->ajaxSuccess();
    }

    /**
     * 流程列表
     * @author sojo
     */
    public function flowList()
    {
        if (request()->isMethod('post')) {
            $params = $this->getRequestParameters(['pageCurrent', 'pageSize']);

            //易管通项目，company_id获取方式不同
//            $companyId = session('current_operation_company_id');
            $adminUser = request()->user('admin')->toArray();
            $companyId = $adminUser['company_id'];

            $flowConfig = new FlowConfig();
            list($flowList, $total) = $flowConfig->getFlowList($companyId, $params['pageCurrent'], $params['pageSize']);

//            debug($flowList);

            return $this->returnPagingData($flowList->toArray(), $params['pageCurrent'], $total);
        }

        return $this->view('flow-list');
    }

    /**
     * 编辑流程
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function flowEdit()
    {
        try {
            $flowId = request('flow_id');
            $flowConfig = new FlowConfig();
            $flowInfo = $flowConfig->getFlowInfo($flowId);

            if (request()->isMethod('post')) {
                $params = $this->getRequestParameters(['flow_id', 'name', 'display'], ['description' => '']);
                $attributes = [
                    'name' => $params['name'],
                    'description' => $params['description'],
                    'display' => $params['display'] == 'true' ? 1 : 0
                ];
                $flowConfig->updateFlowInfo($params['flow_id'], $attributes);

                return $this->ajaxSuccess(null, [
                    'dataGridId' => 'flow-list'
                ]);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }

        return $this->view('flow-edit', compact('flowInfo'));
    }

    /**
     * 流程配置页面
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function flowConfig()
    {
        $params = request()->only('flow_config_id');
        $flowConfig = new FlowConfig();
        $flowConfigList = $flowConfig->getFlowConfigList($params['flow_config_id']);
        return $this->view('flow-config', ['flow_config_id' => $params['flow_config_id'],'flow_config_list' => $flowConfigList]);
    }

    /**
     * 添加流程步骤
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function flowConfigProcessAdd()
    {
        try {
            $params = request(['id', 'oa_flow_config_id', 'operator_id', 'description','button_value']);
            if (request()->isMethod('post')) {
                $flowConfig = new FlowConfig();
                $result = $flowConfig->addFlowConfigProcess($params['id'], $params['oa_flow_config_id'], $params['operator_id'], $params['description']);
                if($result){
                    $flowConfigProcessId = $result;
                    $result = true;
                }

                //追加按钮数据提交
                if($params['button_value']){
                    $flowConfigProcessButtonObj = \App\Eloquent\Oa\FlowConfigProcessButton::firstOrNew(['oa_flow_config_process_id' => $flowConfigProcessId]);
                    $flowConfigProcessButtonUpdateRow = [
                        'oa_flow_config_process_id' => $flowConfigProcessId,
                        'button_value' => $params['button_value'],
                    ];
                    $flowConfigProcessButtonObj->fill($flowConfigProcessButtonUpdateRow);
                    $flowConfigProcessButtonObj->save();
                }

                return $result ? $this->ajaxSuccess() : $this->ajaxFail();
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }

        //按钮列表
        $buttonArr = [];
        $flowId = \App\Eloquent\Oa\FlowConfig::where(['id'=>$params['oa_flow_config_id']])->first()->oa_flow_id;
        if($flowId == 26){
            $buttonArr = [
                '1' => '采购通过',
                '2' => '老板通过',
                '3' => '进行采购',
                '4' => '进行入库',
            ];
        }elseif($flowId == 27){
            $buttonArr = [
                '1' => '退货通过',
                '2' => '老板通过',
                '3' => '进行退货',
                '4' => '进行出库',
            ];
        }

        return $this->view('flow-config-process-add', ['id' => $params['id'], 'oa_flow_config_id' => $params['oa_flow_config_id'],'buttonArr'=>$buttonArr]);
    }

    /**
     * 编辑流程步骤
     * @author wenwenbin
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function flowConfigProcessEdit()
    {
        try {
            $params = request(['id', 'operator_id', 'description','button_value']);
            $flowConfig = new FlowConfig();

            if (request()->isMethod('post')) {
                $result = $flowConfig->editFlowConfigProcess($params['id'], $params['operator_id'], $params['description']);

                //追加按钮数据提交
                $flowConfigProcessId = $params['id'];
                if($params['button_value']){
                    $flowConfigProcessButtonObj = \App\Eloquent\Oa\FlowConfigProcessButton::firstOrNew(['oa_flow_config_process_id' => $flowConfigProcessId]);
                    $flowConfigProcessButtonUpdateRow = [
                        'oa_flow_config_process_id' => $flowConfigProcessId,
                        'button_value' => $params['button_value'],
                    ];
                    $flowConfigProcessButtonObj->fill($flowConfigProcessButtonUpdateRow);
                    $flowConfigProcessButtonObj->save();
                }



                return $result ? $this->ajaxSuccess() : $this->ajaxFail();
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
        $flowConfigProcessInfo = $flowConfig->getFlowConfigProcessInfo($params['id']);

        //获取当前选择的按钮
        $curButtonValue = '';
        $flowConfigProcessId = $flowConfigProcessInfo->id;
        $flowConfigProcessButtonObj = \App\Eloquent\Oa\FlowConfigProcessButton::where(['oa_flow_config_process_id'=>$flowConfigProcessId])->first();
        if($flowConfigProcessButtonObj){
            $curButtonValue = $flowConfigProcessButtonObj->button_value;
        }

        //获取类型id
        $flowId = \App\Eloquent\Oa\FlowConfig::where(['id'=>$flowConfigProcessInfo['oa_flow_config_id']])->first()->oa_flow_id;
        $buttonArr = [];
        if($flowId == 26){
            $buttonArr = [
                '1' => '采购通过',
                '2' => '老板通过',
                '3' => '进行采购',
                '4' => '进行入库',
            ];
        }elseif($flowId == 27){
            $buttonArr = [
                '1' => '退货通过',
                '2' => '老板通过',
                '3' => '进行退货',
                '4' => '进行出库',
            ];
        }

        $flowConfigProcessInfo['buttonArr'] = $buttonArr;
        $flowConfigProcessInfo['defaultButtonValue'] = $curButtonValue;
        return $this->view('flow-config-process-edit', $flowConfigProcessInfo);
    }

    /**
     * 删除流程步骤
     * @author wenwenbin
     * @return \Illuminate\Http\JsonResponse
     */
    public function flowConfigProcessDelete()
    {
        try {
            $params = request(['id']);
            $flowConfig = new FlowConfig();
            $result = $flowConfig->deleteFlowConfigProcess($params['id']);
            return $result ? $this->ajaxSuccess() : $this->ajaxFail();
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
    }

    /**
     * 抄送
     * @author LuLingFeng
     * @return \Illuminate\Http\JsonResponse
     */
    public function copy()
    {
        $params = $this->getRequestParameters(['workflow_id', 'copy_to_ids']);
        $copyToIds = is_array($params['copy_to_ids']) ? $params['copy_to_ids'] : explode(',', $params['copy_to_ids']);
        $copy = new WorkflowCopy();
        $copy->add($params['workflow_id'], $copyToIds);
        return $this->ajaxSuccess();
    }

    /**
     * 流程处理
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function handle()
    {
        if (request()->isMethod('post')) {
            $contacts = AddressList::getContactsAsAdminUser(request());
            if (empty($contacts)) return $this->ajaxFail('无法处理, 账户还未关联到通讯录');
            $workflowId = request('workflow_id', 0);
            $disposeCode = request('dispose_code', 0);
            $assigneeId = request('assignee_id', 0);

            try {
                $workflow = new Workflow();
                $workflow->handle($workflowId, $disposeCode, $contacts->id, $assigneeId);
            } catch (\DebugError $e) {
                return $this->ajaxFail($e->getMessage());
            }

            return $this->ajaxSuccess();
        }

        return $this->view('handle');
    }

    /**
     * 我发起的流程列表
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function myList()
    {
        if (request()->isMethod('get')) {
            return $this->view('my-list');
        }
        $user = request()->user('admin');
        $where = $this->getRequestParameters([], ['type']);
        $companyId = session('current_operation_company_id');
        if (empty($companyId)) xThrow(ERR_UNKNOWN, '数据异常');
        $where['oa_company_id'] = $companyId;
        if ($user['id'] != 1) {
            $contacts = AddressList::getContactsAsAdminUser(request());
            if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
            $where['creator_id'] = $contacts->id;
        }
        $paging = $this->getPagingRequestParameters();
        $workflow = new Workflow();
        return $workflow->workflowList($user->id, $where, $paging);
    }

    /**
     * 我待办的流程列表
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function todoList()
    {
        if (request()->isMethod('get')) {
            return $this->view('todo-list');
        }
        $user = request()->user('admin');
        $where = $this->getRequestParameters([], ['type']);
        $companyId = session('current_operation_company_id');
        if (empty($companyId)) xThrow(ERR_UNKNOWN, '数据异常');
        $where['oa_company_id'] = $companyId;
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
        $where['assignee_id'] = $contacts->id;
        $where['is_workflow_end'] = 0;
        $paging = $this->getPagingRequestParameters();
        $workflow = new Workflow();
        return $workflow->workflowList($user->user_id, $where, $paging);
    }

    /**
     * 我已办的流程列表
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function doneList()
    {
        if (request()->isMethod('get')) {
            return $this->view('done-list');
        }
        $user = request()->user('admin');
        $where = $this->getRequestParameters([], ['type']);
        $companyId = session('current_operation_company_id');
        if (empty($companyId)) xThrow(ERR_UNKNOWN, '数据异常');
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
        $where['oa_company_id'] = $companyId;
        $where['log_operator_id'] = $contacts->id;
        $where['not_creator_id'] = $contacts->id;
        $paging = $this->getPagingRequestParameters();
        $workflow = new Workflow();
        return $workflow->workflowList($user->user_id, $where, $paging);
    }

    /**
     * 抄送我的列表
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function copyList()
    {
        if (request()->isMethod('get')) {
            return $this->view('copy-list');
        }
        $user = request()->user('admin');
        $where = $this->getRequestParameters([], ['type']);
        $companyId = session('current_operation_company_id');
        if (empty($companyId)) xThrow(ERR_UNKNOWN, '数据异常');
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
        $where['oa_company_id'] = $companyId;
        $where['copy_to_id'] = $contacts->id;
        $paging = $this->getPagingRequestParameters();
        $workflow = new Workflow();
        return $workflow->workflowList($user->user_id, $where, $paging);
    }

    /**
     * 办理完结的列表
     * @author sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function endList()
    {
        if (request()->isMethod('get')) {
            return $this->view('end-list');
        }
        $user = request()->user('admin');
        $where = $this->getRequestParameters([], ['type']);
        $companyId = session('current_operation_company_id');
        if (empty($companyId)) xThrow(ERR_UNKNOWN, '数据异常');
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
        $where['oa_company_id'] = $companyId;
        $where['log_operator_id'] = $contacts->id;
        $where['dispose_code'] = 1100;
        $paging = $this->getPagingRequestParameters();
        $workflow = new Workflow();
        return $workflow->workflowList($user->user_id, $where, $paging);
    }

    /**
     * 上传附件
     * @author LuLingFeng
     * @return array
     */
    public function uploadEnclosure()
    {
        $data = Upload::uploadFile(request()->file('file'), 'oa/workflow/enclosure', null, '');
        \DebugBar::disable();
        return [
            'statusCode' => 200,
            'filename' => '/' . $data['fullPath']
        ];
    }

    /**
     * 详情
     * @author LuLingFeng
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail()
    {
        $contacts = AddressList::getContactsAsAdminUser(request());
        if (empty($contacts)) return $this->ajaxFail('无法查看, 账户还未关联到通讯录');
        $params = $this->getRequestParameters(['workflow_id']);
        $data = (new Workflow())->detail($contacts->id, $params['workflow_id']);
        return $this->view('detail-' . $data['relate_type_abbr'], $data);
    }
}